
/**
 * 移动端友好的通知系统
 * 支持：Toast提示、震动、声音、标题栏提醒、页面内提示条
 */

const NotificationManager = {
    config: {
        enableVibration: true,          // 是否启用震动
        enableSound: true,              // 是否启用声音
        enableTitleBadge: true,         // 是否启用标题栏徽标
        enableToast: true,              // 是否启用Toast
        enableBanner: true,             // 是否启用横幅提示
        enableBrowserNotification: true, // 是否启用浏览器通知
        soundVolume: 0.7,               // 音量 0-1
        vibrationPattern: [200, 100, 200], // 震动模式
    },
    
    state: {
        originalTitle: document.title,
        titleInterval: null,
        unreadCount: 0,
        soundLoaded: false,
        audio: null
    },
    
    // 初始化
    init: function() {
        this.detectCapabilities();
        this.loadSound();
        this.loadSettings();
        this.initBannerContainer();
        
        // 页面获得焦点时恢复标题
        window.addEventListener('focus', () => {
            this.clearTitleNotification();
        });
        
    },
    
    // 检测设备能力
    detectCapabilities: function() {
        const capabilities = {
            vibration: 'vibrate' in navigator,
            notification: 'Notification' in window,
            audio: typeof Audio !== 'undefined',
            isMobile: DeviceDetector.isMobile() // 使用统一的设备检测
        };
        
        this.capabilities = capabilities;
        
        // 移动端自动禁用浏览器通知，启用其他方式
        if (capabilities.isMobile) {
            this.config.enableBrowserNotification = false;
        }
    },
    
    // 加载提示音
    loadSound: function() {
        if (!this.capabilities.audio) {
            console.warn('浏览器不支持音频播放');
            return;
        }
        
        try {
            // 使用 Data URI 内嵌一个简短的提示音（避免网络请求）
            // 这是一个简单的 beep 音效（440Hz，0.2秒）
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            this.audioContext = audioContext;
            this.state.soundLoaded = true;
        } catch (error) {
            console.warn('加载提示音失败:', error);
        }
    },
    
    // 播放提示音
    playSound: function() {
        if (!this.config.enableSound || !this.state.soundLoaded) return;
        
        try {
            const ctx = this.audioContext;
            const oscillator = ctx.createOscillator();
            const gainNode = ctx.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(ctx.destination);
            
            oscillator.frequency.value = 800; // 频率
            oscillator.type = 'sine';
            
            gainNode.gain.setValueAtTime(this.config.soundVolume, ctx.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.2);
            
            oscillator.start(ctx.currentTime);
            oscillator.stop(ctx.currentTime + 0.2);
        } catch (error) {
            console.error('播放提示音失败:', error);
        }
    },
    
    // 震动提醒
    vibrate: function() {
        if (!this.config.enableVibration || !this.capabilities.vibration) return;
        
        try {
            navigator.vibrate(this.config.vibrationPattern);
        } catch (error) {
            console.error('震动失败:', error);
        }
    },
    
    // 标题栏闪烁提醒
    updateTitleNotification: function(message) {
        if (!this.config.enableTitleBadge) return;
        
        // 清除之前的闪烁
        this.clearTitleNotification();
        
        let isOriginal = true;
        let flashCount = 0;
        const maxFlashes = 10;
        
        this.state.titleInterval = setInterval(() => {
            document.title = isOriginal ? message : this.state.originalTitle;
            isOriginal = !isOriginal;
            flashCount++;
            
            // 达到最大闪烁次数后自动停止
            if (flashCount >= maxFlashes) {
                this.clearTitleNotification();
            }
        }, 1000);
    },
    
    // 清除标题栏提醒
    clearTitleNotification: function() {
        if (this.state.titleInterval) {
            clearInterval(this.state.titleInterval);
            this.state.titleInterval = null;
            document.title = this.state.originalTitle;
        }
    },
    
    // 初始化横幅容器
    initBannerContainer: function() {
        if ($('#notification-banner-container').length === 0) {
            $('body').append(`
                <div id="notification-banner-container" style="
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    z-index: 99999;
                    pointer-events: none;
                "></div>
            `);
        }
    },
    
    // 显示页面内横幅提示（iOS风格）
    showBanner: function(title, message, options = {}) {
        if (!this.config.enableBanner) return;
        
        const icon = options.icon || '📧';
        const duration = options.duration || 4000;
        
        const bannerId = 'banner-' + Date.now();
        const banner = $(`
            <div id="${bannerId}" class="notification-banner" style="
                background: rgba(255, 255, 255, 0.95);
                backdrop-filter: blur(10px);
                -webkit-backdrop-filter: blur(10px);
                border-radius: 12px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                margin: 10px;
                padding: 12px 16px;
                display: flex;
                align-items: center;
                gap: 12px;
                pointer-events: auto;
                cursor: pointer;
                transform: translateY(-100%);
                opacity: 0;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            ">
                <div style="
                    font-size: 32px;
                    flex-shrink: 0;
                ">${icon}</div>
                <div style="
                    flex: 1;
                    min-width: 0;
                ">
                    <div style="
                        font-weight: 600;
                        font-size: 14px;
                        color: #333;
                        margin-bottom: 2px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    ">${title}</div>
                    <div style="
                        font-size: 13px;
                        color: #666;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    ">${message}</div>
                </div>
                <div style="
                    font-size: 20px;
                    color: #999;
                    flex-shrink: 0;
                ">×</div>
            </div>
        `);
        
        $('#notification-banner-container').append(banner);
        
        // 触发动画
        setTimeout(() => {
            banner.css({
                transform: 'translateY(0)',
                opacity: 1
            });
        }, 10);
        
        // 点击关闭
        banner.on('click', function() {
            $(this).css({
                transform: 'translateY(-100%)',
                opacity: 0
            });
            setTimeout(() => $(this).remove(), 300);
        });
        
        // 自动关闭
        setTimeout(() => {
            banner.css({
                transform: 'translateY(-100%)',
                opacity: 0
            });
            setTimeout(() => banner.remove(), 300);
        }, duration);
    },
    
    // Toast提示（使用layui）
    showToast: function(message, options = {}) {
        if (!this.config.enableToast) return;
        
        const icon = options.icon || 1;
        const time = options.time || 3000;
        const offset = options.offset || 'rb'; // 右下角
        
        layui.layer.msg(message, {
            icon: icon,
            time: time,
            offset: offset,
            closeBtn: 1,
            anim: 0
        });
    },
    
    // 综合通知方法（新邮件专用：横幅+声音+浏览器通知）
    notify: function(title, message, options = {}) {
        const isMobile = this.capabilities.isMobile;
        const isPageVisible = !document.hidden;
        
        // 新邮件通知策略：横幅 + 声音 + 浏览器通知（多重提醒）
        
        // 1. 横幅提示（页面可见时显示）
        if (isPageVisible) {
            // 横幅使用 emoji 图标，不使用图片URL
            this.showBanner(title, message, {
                icon: options.bannerIcon || '📧',
                duration: options.duration
            });
        }
        
        // 2. 声音提示（始终播放）
        this.playSound();
        
        // 3. 震动（仅移动端）
        if (isMobile) {
            this.vibrate();
        }
        
        // 4. 浏览器通知（页面不可见时或PC端）
        if (!isPageVisible || !isMobile) {
            if (this.config.enableBrowserNotification &&
                this.capabilities.notification &&
                Notification.permission === 'granted') {
                try {
                    new Notification(title, {
                        body: message,
                        icon: options.icon || 'images/user-avatar.png',
                        badge: options.badge,
                        tag: options.tag || 'email-notification'
                    });
                } catch (error) {
                    console.warn('浏览器通知失败:', error);
                }
            }
        }
        
        // 5. 标题栏闪烁（页面不可见时）
        if (!isPageVisible) {
            this.updateTitleNotification(`📧 ${title}`);
        }
    },
    
    // 清除未读数
    clearUnreadCount: function() {
        this.state.unreadCount = 0;
        this.clearTitleNotification();
        // 恢复原始favicon（可选）
    },
    
    // 加载用户设置
    loadSettings: function() {
        try {
            const settings = JSON.parse(localStorage.getItem('notificationSettings') || '{}');
            Object.assign(this.config, settings);
        } catch (error) {
            console.warn('加载通知设置失败:', error);
        }
    },
    
    // 保存用户设置
    saveSettings: function() {
        try {
            localStorage.setItem('notificationSettings', JSON.stringify(this.config));
        } catch (error) {
            console.error('保存通知设置失败:', error);
        }
    },
    
    // 显示设置面板
    showSettingsPanel: function() {
        // 检查各项功能支持情况
        const isMobile = this.capabilities.isMobile;
        const vibrationSupported = this.capabilities.vibration && isMobile; // PC端禁用震动
        const soundSupported = this.capabilities.audio;
        const notificationSupported = this.capabilities.notification;
        const notificationPermission = notificationSupported ? Notification.permission : 'denied';
        
        // 构建浏览器通知的提示文本
        let browserNotifHint = '';
        if (!notificationSupported) {
            browserNotifHint = ' <span style="color: #999; font-size: 12px;">(不支持)</span>';
        } else if (notificationPermission === 'denied') {
            browserNotifHint = ' <span style="color: #ff5722; font-size: 12px;">(已拒绝)</span>';
        } else if (notificationPermission === 'default') {
            browserNotifHint = ' <span style="color: #ff9800; font-size: 12px;">(需授权)</span>';
        } else {
            browserNotifHint = ' <span style="color: #4caf50; font-size: 12px;">(已授权)</span>';
        }
        
        const html = `
            <div style="padding: 20px;">
                <div style="margin-bottom: 15px; display: flex; align-items: center; justify-content: space-between;">
                    <label style="display: flex; align-items: center; cursor: pointer; flex: 1;">
                        <input type="checkbox" id="enable-toast" ${this.config.enableToast ? 'checked' : ''}
                               style="margin-right: 8px;"> Toast消息提示
                    </label>
                    <button class="layui-btn layui-btn-xs" data-test="toast">测试</button>
                </div>
                <div style="margin-bottom: 15px; display: flex; align-items: center; justify-content: space-between;">
                    <label style="display: flex; align-items: center; cursor: pointer; flex: 1;">
                        <input type="checkbox" id="enable-banner" ${this.config.enableBanner ? 'checked' : ''}
                               style="margin-right: 8px;"> 页面顶部横幅
                    </label>
                    <button class="layui-btn layui-btn-xs" data-test="banner">测试</button>
                </div>
                <div style="margin-bottom: 15px; display: flex; align-items: center; justify-content: space-between;">
                    <label style="display: flex; align-items: center; cursor: ${vibrationSupported ? 'pointer' : 'not-allowed'}; flex: 1; opacity: ${vibrationSupported ? 1 : 0.5};">
                        <input type="checkbox" id="enable-vibration" ${this.config.enableVibration ? 'checked' : ''}
                               ${vibrationSupported ? '' : 'disabled'}
                               style="margin-right: 8px;"> 震动提醒${vibrationSupported ? '' : ' <span style="color: #999; font-size: 12px;">(不支持)</span>'}
                    </label>
                    <button class="layui-btn layui-btn-xs" data-test="vibration" ${vibrationSupported ? '' : 'disabled'}>测试</button>
                </div>
                <div style="margin-bottom: 15px; display: flex; align-items: center; justify-content: space-between;">
                    <label style="display: flex; align-items: center; cursor: ${soundSupported ? 'pointer' : 'not-allowed'}; flex: 1; opacity: ${soundSupported ? 1 : 0.5};">
                        <input type="checkbox" id="enable-sound" ${this.config.enableSound ? 'checked' : ''}
                               ${soundSupported ? '' : 'disabled'}
                               style="margin-right: 8px;"> 声音提示${soundSupported ? '' : ' <span style="color: #999; font-size: 12px;">(不支持)</span>'}
                    </label>
                    <button class="layui-btn layui-btn-xs" data-test="sound" ${soundSupported ? '' : 'disabled'}>测试</button>
                </div>
                <div style="margin-bottom: 15px; display: flex; align-items: center; justify-content: space-between;">
                    <label style="display: flex; align-items: center; cursor: pointer; flex: 1;">
                        <input type="checkbox" id="enable-title-badge" ${this.config.enableTitleBadge ? 'checked' : ''}
                               style="margin-right: 8px;"> 标题栏闪烁
                    </label>
                    <button class="layui-btn layui-btn-xs" data-test="title">测试</button>
                </div>
                <div style="margin-bottom: 15px; display: flex; align-items: center; justify-content: space-between;">
                    <label style="display: flex; align-items: center; cursor: ${notificationSupported && notificationPermission !== 'denied' ? 'pointer' : 'not-allowed'}; flex: 1; opacity: ${notificationSupported && notificationPermission !== 'denied' ? 1 : 0.5};">
                        <input type="checkbox" id="enable-browser-notification"
                               ${this.config.enableBrowserNotification && notificationPermission === 'granted' ? 'checked' : ''}
                               ${notificationSupported && notificationPermission !== 'denied' ? '' : 'disabled'}
                               style="margin-right: 8px;"> 浏览器通知${browserNotifHint}
                    </label>
                    <button class="layui-btn layui-btn-xs" data-test="browser-notification"
                            ${notificationSupported && notificationPermission === 'granted' ? '' : 'disabled'}>测试</button>
                </div>
                ${notificationPermission === 'default' ? `
                <div style="margin-bottom: 15px; padding: 10px; background: #fff3e0; border-radius: 4px; font-size: 12px; color: #ff6f00;">
                    <i class="layui-icon layui-icon-tips"></i> 浏览器通知需要您的授权。
                    <button class="layui-btn layui-btn-xs layui-btn-warm" id="request-notification-permission" style="margin-left: 10px;">
                        申请权限
                    </button>
                </div>
                ` : ''}
                <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee;">
                    <button class="layui-btn layui-btn-sm layui-btn-normal" style="width: 100%; margin-bottom: 10px;" id="test-all-notification-btn">
                        <i class="layui-icon layui-icon-speaker"></i> 测试所有通知
                    </button>
                    <div style="display: flex; gap: 10px;">
                        <button class="layui-btn layui-btn-sm" style="flex: 1;" id="test-new-mail-notification-btn">
                            <i class="layui-icon layui-icon-email"></i> 测试新邮件通知
                        </button>
                        <button class="layui-btn layui-btn-sm layui-btn-warm" style="flex: 1;" id="test-sync-success-notification-btn">
                            <i class="layui-icon layui-icon-ok-circle"></i> 测试同步成功
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // 使用统一的设备检测
        const isMobileDevice = DeviceDetector.isMobile();
        
        const index = layui.layer.open({
            type: 1,
            title: '通知设置',
            content: html,
            area: isMobileDevice ? ['100%', '100%'] : ['500px', 'auto'],
            btn: ['保存', '取消'],
            yes: (idx) => {
                this.config.enableToast = $('#enable-toast').prop('checked');
                this.config.enableBanner = $('#enable-banner').prop('checked');
                this.config.enableVibration = $('#enable-vibration').prop('checked');
                this.config.enableSound = $('#enable-sound').prop('checked');
                this.config.enableTitleBadge = $('#enable-title-badge').prop('checked');
                this.config.enableBrowserNotification = $('#enable-browser-notification').prop('checked');
                
                this.saveSettings();
                layui.layer.msg('设置已保存', { icon: 1 });
                layui.layer.close(idx);
            }
        });
        
        // 申请浏览器通知权限
        $(document).on('click', '#request-notification-permission', () => {
            if (notificationSupported && Notification.permission === 'default') {
                Notification.requestPermission().then((permission) => {
                    if (permission === 'granted') {
                        layui.layer.msg('通知权限已授予', { icon: 1 });
                        // 关闭当前弹窗并重新打开以刷新状态
                        layui.layer.close(index);
                        setTimeout(() => this.showSettingsPanel(), 300);
                    } else {
                        layui.layer.msg('通知权限被拒绝', { icon: 2 });
                    }
                });
            }
        });
        
        // 单独测试每种通知方式
        $(document).on('click', '[data-test]', (e) => {
            const type = $(e.currentTarget).data('test');
            
            switch(type) {
                case 'toast':
                    this.showToast('这是Toast消息提示测试', { icon: 1 });
                    break;
                case 'banner':
                    this.showBanner('横幅测试', '这是页面顶部横幅提示测试', { icon: '🔔' });
                    break;
                case 'vibration':
                    this.vibrate();
                    layui.layer.msg('已触发震动（如果设备支持）', { icon: 1, time: 1500 });
                    break;
                case 'sound':
                    this.playSound();
                    layui.layer.msg('已播放提示音', { icon: 1, time: 1500 });
                    break;
                case 'title':
                    this.updateTitleNotification('📧 新邮件提醒测试');
                    layui.layer.msg('标题栏正在闪烁，请查看浏览器标签', { icon: 1, time: 2000 });
                    // 3秒后自动清除
                    setTimeout(() => this.clearTitleNotification(), 3000);
                    break;
                case 'browser-notification':
                    if (notificationSupported && Notification.permission === 'granted') {
                        try {
                            new Notification('浏览器通知测试', {
                                body: '这是浏览器原生通知测试',
                                icon: 'images/user-avatar.png',
                                tag: 'test-notification'
                            });
                        } catch (error) {
                            layui.layer.msg('浏览器通知发送失败', { icon: 2 });
                        }
                    }
                    break;
            }
        });
        
        // 测试所有通知（模拟真实新邮件通知）
        $(document).on('click', '#test-all-notification-btn', () => {
            const testTitle = '新邮件测试';
            const testMessage = '测试账号收到1封新邮件';
            
            // 1. 横幅（如果启用且页面可见）
            if (this.config.enableBanner && !document.hidden) {
                this.showBanner(testTitle, testMessage, { icon: '📧' });
            }
            
            // 2. 声音（如果启用）
            if (this.config.enableSound && soundSupported) {
                this.playSound();
            }
            
            // 3. 震动（如果启用且为移动端）
            if (this.config.enableVibration && vibrationSupported) {
                this.vibrate();
            }
            
            // 4. 浏览器通知（如果启用且已授权）
            if (this.config.enableBrowserNotification &&
                notificationSupported &&
                notificationPermission === 'granted') {
                try {
                    new Notification(testTitle, {
                        body: testMessage,
                        icon: 'images/user-avatar.png',
                        tag: 'test-all-notification'
                    });
                } catch (error) {
                    console.warn('浏览器通知测试失败:', error);
                }
            }
            
            // 5. Toast提示（作为反馈）
            if (this.config.enableToast) {
                setTimeout(() => {
                    this.showToast('所有已启用的通知方式已测试完成', { icon: 1 });
                }, 500);
            }
        });
        
        // 测试新邮件通知（使用debug模块的默认参数）
        $(document).on('click', '#test-new-mail-notification-btn', () => {
            if (typeof App !== 'undefined' && App.debug && App.debug.sendTestNotification) {
                App.debug.sendTestNotification(1, 'INBOX', 2);
            } else {
                layui.layer.msg('调试模块未加载', { icon: 2 });
            }
        });
        
        // 测试同步成功通知（使用debug模块的默认参数）
        $(document).on('click', '#test-sync-success-notification-btn', () => {
            if (typeof App !== 'undefined' && App.debug && App.debug.sendSyncSuccessNotification) {
                App.debug.sendSyncSuccessNotification(1, 3);
            } else {
                layui.layer.msg('调试模块未加载', { icon: 2 });
            }
        });
    }
};

// 向全局暴露简化的通知函数
window.showNotification = function(title, options = {}) {
    const message = options.body || title;
    NotificationManager.notify(title, message, {
        icon: options.icon,
        updateUnreadCount: options.updateUnreadCount
    });
};

// 页面加载完成后初始化
$(document).ready(function() {
    NotificationManager.init();
    
    // 将通知管理器挂载到全局以便调试
    window.NotificationManager = NotificationManager;
});